package com.xhis.homenurse.webservice.convert;

import android.util.Log;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by user041 on 2019/7/18.
 */

final class MyXmlResponseBodyConverter<T> implements Converter<ResponseBody, T>
{
    private Class<?> clazz;

    MyXmlResponseBodyConverter(Type clazz) {
        this.clazz = (Class<?>) clazz;
    }

    @Override public T convert(ResponseBody value) throws IOException
    {
//         BufferedSource source = value.source();
//         source.request(Long.MAX_VALUE);
//         Buffer buffer = source.buffer();
//         buffer.clone().readString(Charset.forName("UTF-8"))
        String outXml = value.string();
        Log.e("ResponseBody",outXml);

        try {
            //return adapter.fromJson(obj.toString());
            //return (T) obj.toString();
            Object resultObj = null;
            Method[] methods = clazz.getMethods();
            // 利用反射向不同类中的有相同方法名的方法中传入从服务器返回的outXml
            for (Method m : methods) {
                if (m.getName().equals("getOutData")) {
                    resultObj = clazz.newInstance();
                    m.invoke(resultObj, outXml);
                }
            }
            return (T) resultObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            value.close();
        }
    }
}
